package router

import (
	"github.com/gin-gonic/gin"
	"logi-flow/handler"
	"logi-flow/pkg"
	"net/http"
)

func Router() *gin.Engine {
	// 1.创建路由
	r := gin.Default()
	r.Use(Cors()) //默认跨域
	r.Static("/static", "./static")
	r.POST("/login", handler.Login)
	r.POST("/roleNodeAdd", handler.RoleNodeAdd)
	r.GET("/userRole", handler.UserRole)
	r.GET("/RoleNode", handler.RoleNode)
	r.POST("/personAdd", handler.PersonAdd)
	r.POST("/personOrderAdd", handler.PersonOrderAdd)
	r.GET("/personOrderList", handler.PersonOrderList)
	r.GET("/personOrderDetail", handler.PersonOrderDetail)
	r.POST("/info", MiddleWare(), handler.Info)

	r.POST("/userLogin", handler.UserLogin)
	r.POST("/userRegister", handler.UserRegister)
	r.GET("/personOrderSelect", handler.PersonOrderSelect)
	r.POST("/userRoleAdd", handler.UserRoleAdd)
	r.GET("/userRoleList", handler.UserRoleList)

	return r
}
func MiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenStrig := c.Request.Header.Get("token")
		if tokenStrig == "" {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "不能为空",
			})
			c.Abort()
		}
		token, err := pkg.GetToken(tokenStrig)
		if err != "" {
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "解密失败",
			})
			c.Abort()
		}
		c.Set("uid", token["uid"])
		c.Next()
	}
}
func Cors() gin.HandlerFunc {

	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != "" {
			c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
			c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization")
			c.Header("Access-Control-Allow-Credentials", "true")
			c.Set("content-type", "application/json")
		}
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}
